package jkCore.social.ad.adapter;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdListener;
import com.applovin.mediation.MaxAdRevenueListener;
import com.applovin.mediation.MaxAdViewAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.MaxRewardedAdListener;
import com.applovin.mediation.ads.MaxAdView;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.applovin.mediation.ads.MaxRewardedAd;
import com.applovin.sdk.AppLovinMediationProvider;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkConfiguration;

import jkCore.social.ad.AdManager;
import jkCore.utils.Utils;
//import JKCore.SocialManager.analytics.AnalyticsManager;

import org.json.JSONObject;

import java.util.HashMap;

public class MAXAdapter extends AdBaseAdapter {

    private static final String TAG = "MAX";
    private static final int MSG_LOAD_INTER = 100;

    private MaxAdView mBannerAd;
    private MaxInterstitialAd mInterstitialAd;
    private MaxRewardedAd mRewardVideoAd;
    private int mBannerHeight;

    static {
        AdManager.ins().addAdapter(new MAXAdapter());
    }

    @Override
    public void initAd(Activity context) {
        super.initAd(context);
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] Init Ad - " + mConfigValue.toString());
        }
        if (TextUtils.isEmpty(mConfigValue.appId)) {
            return;
        }
        AppLovinSdk.getInstance(context).setMediationProvider(AppLovinMediationProvider.MAX);
        AppLovinSdk.initializeSdk(context, new AppLovinSdk.SdkInitializationListener() {
            @Override
            public void onSdkInitialized(AppLovinSdkConfiguration config) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - Init] onSdkInitialized : " + config.getConsentDialogState());
                }
                loadAllAds();
            }
        });
//        AppLovinSdk.getInstance(context).showMediationDebugger();
    }

    public String adName() {
        return TAG;
    }

    public boolean isOut() {
        return true;
    }

    @Override
    public void showBanner(AdManager.AdCallBack callBack) {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] showBanner");
        }
        isTryShowBanner = true;
        adBannerCallBack = callBack;
        if (mBannerAd != null) {
            Utils.removeSelfFromParent(mBannerAd);
            FrameLayout.LayoutParams frameLayout = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mBannerHeight);
            frameLayout.gravity = Gravity.BOTTOM | Gravity.CENTER;
            mActivity.addContentView(mBannerAd, frameLayout);
            mBannerAd.setVisibility(View.VISIBLE);
            mBannerAd.startAutoRefresh();
            if (adBannerCallBack != null) {
                adBannerCallBack.onStart(new JSONObject());
            }
        } else {
            loadBannerAds();
        }
    }

    @Override
    public void hideBanner() {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] hideBanner");
        }
        isTryShowBanner = false;
        if (mBannerAd != null && mBannerAd.getVisibility() == View.VISIBLE) {
            Utils.removeSelfFromParent(mBannerAd);
            mBannerAd.setVisibility(View.GONE);
            mBannerAd.stopAutoRefresh();
            if (adBannerCallBack != null) {
                adBannerCallBack.onFinish(new JSONObject());
                adBannerCallBack = null;
            }
            loadBannerAds();
        }
    }

    @Override
    public void showInter(AdManager.AdCallBack callBack) {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] showInter");
        }
        adInterCallBack = callBack;
        if (mInterstitialAd != null && mInterstitialAd.isReady()) {
            mInterstitialAd.showAd();
        } else {
            loadInterAds();
        }
    }

    @Override
    public boolean isVideoReady() {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] isVideoReady:" + isVideoReady);
        }
        if (!isInit) {
            return false;
        }
        if (mRewardVideoAd == null || (!isVideoReady && !isVideoLoading)) {
            loadRewardAds();
        }
        return isVideoReady;
    }

    @Override
    public void showVideo(AdManager.AdCallBack callBack) {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] showVideo");
        }
        adVideoCallBack = callBack;
        if (mRewardVideoAd != null && mRewardVideoAd.isReady()) {
            isVideoPlayFinish = false;
            mRewardVideoAd.showAd();
        } else {
            loadRewardAds();
        }
    }

    @Override
    public void onDestroy() {
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] onDestroy");
        }
        if (mBannerAd != null) {
            mBannerAd.destroy();
        }
    }

    @Override
    public void loadBannerAds() {
        Log.i(TOP_TAG, isInit+ "isInit" + isBannerLoading+"isBannerLoading" + isRemoveAds+"isRemoveAds");
        if (!isInit || isBannerLoading || isRemoveAds) {
            return;
        }
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] loadBannerAds");
        }
        Log.i(TOP_TAG, mConfigValue.bannerKey);
        if (TextUtils.isEmpty(mConfigValue.bannerKey)) {
            return;
        }
        if (mBannerAd != null) {
            mBannerAd.destroy();
            mBannerAd = null;
        }
        mBannerAd = new MaxAdView(mConfigValue.bannerKey, mActivity);
        mBannerHeight = (int) (50 * mActivity.getResources().getDisplayMetrics().scaledDensity);
        mBannerAd.setLayoutParams(new FrameLayout.LayoutParams(mActivity.getResources().getDisplayMetrics().widthPixels, mBannerHeight));
        mBannerAd.setListener(new MaxAdViewAdListener() {
            @Override
            public void onAdExpanded(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdExpanded");
                }
            }

            @Override
            public void onAdCollapsed(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdCollapsed");
                }
            }

            @Override
            public void onAdLoaded(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdLoaded");
                }
                isBannerReady = true;
                isBannerLoading = false;
                mBannerAd.stopAutoRefresh();
                if (isTryShowBanner) {
                    showBanner(adBannerCallBack);
                }
            }

            @Override
            public void onAdLoadFailed(String adUnitId, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdLoadFailed : " + error.getMessage());
                }
                isBannerReady = false;
                isBannerLoading = false;
            }

            @Override
            public void onAdDisplayed(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdDisplayed");
                }
                if (adBannerCallBack != null) {
                    adBannerCallBack.onStart(new JSONObject());
                }
            }

            @Override
            public void onAdHidden(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdHidden");
                }
            }

            @Override
            public void onAdClicked(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdClicked");
                }
                if (adBannerCallBack != null) {
                    adBannerCallBack.onClick(new JSONObject());
                }
            }

            @Override
            public void onAdDisplayFailed(MaxAd ad, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdDisplayFailed : " + error.getMessage());
                }
            }
        });
        mBannerAd.setRevenueListener(new MaxAdRevenueListener() {
            @Override
            public void onAdRevenuePaid(MaxAd maxAd) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - BannerAd] onAdRevenuePaid : " + maxAd.toString());
                }
                HashMap<String, Object> adRevenue = new HashMap<String, Object>();
                adRevenue.put("value", maxAd.getRevenue());
                adRevenue.put("currency", "USD");
                adRevenue.put("ad_network", maxAd.getNetworkName());
                adRevenue.put("ad_format", maxAd.getFormat().getLabel());
//                AnalyticsManager.ins().reportEvent("iaa_revenue", adRevenue);
            }
        });
        isBannerReady = false;
        isBannerLoading = true;
        mBannerAd.loadAd();
    }

    @Override
    public void loadInterAds() {
        if (!isInit || isInterLoading || isRemoveAds) {
            return;
        }
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] loadInterAds");
        }
        if (TextUtils.isEmpty(mConfigValue.interKey)) {
            return;
        }
        mInterstitialAd = new MaxInterstitialAd(mConfigValue.interKey, mActivity);
        mInterstitialAd.setListener(new MaxAdListener() {
            @Override
            public void onAdLoaded(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdLoaded");
                }
                isInterReady = true;
                isInterLoading = false;
                finishTryLoadInterAds();
            }

            @Override
            public void onAdLoadFailed(String adUnitId, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdLoadFailed : " + error.getMessage());
                }
                isInterReady = false;
                isInterLoading = false;
                tryLoadInterAds();
            }

            @Override
            public void onAdDisplayed(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdDisplayed");
                }
                if (adInterCallBack != null) {
                    adInterCallBack.onStart(new JSONObject());
                }
            }

            @Override
            public void onAdHidden(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdHidden");
                }
                if (adInterCallBack != null) {
                    adInterCallBack.onFinish(new JSONObject());
                    adInterCallBack = null;
                }
                loadInterAds();
            }

            @Override
            public void onAdClicked(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdClicked");
                }
                if (adInterCallBack != null) {
                    adInterCallBack.onClick(new JSONObject());
                }
            }

            @Override
            public void onAdDisplayFailed(MaxAd ad, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdDisplayFailed : " + error.getMessage());
                }
            }
        });
        mInterstitialAd.setRevenueListener(new MaxAdRevenueListener() {
            @Override
            public void onAdRevenuePaid(MaxAd maxAd) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdRevenuePaid : " + maxAd.toString());
                }
                HashMap<String, Object> adRevenue = new HashMap<String, Object>();
                adRevenue.put("value", maxAd.getRevenue());
                adRevenue.put("currency", "USD");
                adRevenue.put("ad_network", maxAd.getNetworkName());
                adRevenue.put("ad_format", maxAd.getFormat().getLabel());
//                AnalyticsManager.ins().reportEvent("iaa_revenue", adRevenue);
            }
        });
        isInterLoading = true;
        isInterReady = false;
        mInterstitialAd.loadAd();
    }

    @Override
    public void loadRewardAds() {
        if (!isInit || isVideoLoading) {
            return;
        }
        if (isDebug) {
            Log.i(TOP_TAG, "[" + TAG + "] loadRewardAds");
        }
        if (TextUtils.isEmpty(mConfigValue.videoKey)) {
            return;
        }
        mRewardVideoAd = MaxRewardedAd.getInstance(mConfigValue.videoKey, mActivity);
        mRewardVideoAd.setListener(new MaxRewardedAdListener() {
            @Override
            public void onRewardedVideoStarted(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onRewardedVideoStarted");
                }
                isVideoPlayFinish = false;
                if (adVideoCallBack != null) {
                    adVideoCallBack.onStart(new JSONObject());
                }
            }

            @Override
            public void onRewardedVideoCompleted(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onRewardedVideoCompleted");
                }
            }

            @Override
            public void onUserRewarded(MaxAd ad, MaxReward reward) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onUserRewarded");
                }
                isVideoPlayFinish = true;
            }

            @Override
            public void onAdLoaded(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onAdLoaded");
                }
                isVideoReady = true;
                isVideoLoading = false;
            }

            @Override
            public void onAdLoadFailed(String adUnitId, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onAdLoadFailed :" + error.getMessage());
                }
                isVideoReady = false;
                isVideoLoading = false;
            }

            @Override
            public void onAdDisplayed(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onRewardedVideoCompleted");
                }
            }

            @Override
            public void onAdHidden(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onAdHidden");
                }
                if (adVideoCallBack != null) {
                    JSONObject ret = new JSONObject();
                    try {
                        ret.put("Status", isVideoPlayFinish);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    adVideoCallBack.onFinish(ret);
                    adVideoCallBack = null;
                }
                loadRewardAds();
            }

            @Override
            public void onAdClicked(MaxAd ad) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onAdClicked");
                }
                if (adVideoCallBack != null) {
                    adVideoCallBack.onClick(new JSONObject());
                }
            }

            @Override
            public void onAdDisplayFailed(MaxAd ad, MaxError error) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - VideoAd] onAdDisplayFailed : " + error.getMessage());
                }
                isVideoPlayFinish = false;
            }
        });
        mRewardVideoAd.setRevenueListener(new MaxAdRevenueListener() {
            @Override
            public void onAdRevenuePaid(MaxAd maxAd) {
                if (isDebug) {
                    Log.i(TOP_TAG, "[" + TAG + " - InterAd] onAdRevenuePaid : " + maxAd.toString());
                }
                HashMap<String, Object> adRevenue = new HashMap<String, Object>();
                adRevenue.put("value", maxAd.getRevenue());
                adRevenue.put("currency", "USD");
                adRevenue.put("ad_network", maxAd.getNetworkName());
                adRevenue.put("ad_format", maxAd.getFormat().getLabel());
//                AnalyticsManager.ins().reportEvent("iaa_revenue", adRevenue);
            }
        });
        isVideoReady = false;
        isVideoLoading = true;
        mRewardVideoAd.loadAd();
    }
}
